<template>
  <div class="doctor-container">

    <div v-if="hasValidUser">
    </div>

    <div v-if="!userStore?.isLoggedIn" class="auth-required">
      <h2>请先登录</h2>
      <button @click="goToLogin" class="login-btn">前往登录</button>
    </div>


    <div v-else class="main-content">
      <div class="patient-selection">
        <h2>选择患者</h2>
        <el-select v-model="selectedPatientId" placeholder="请选择患者" @change="loadPatientData">
          <el-option
              v-for="patient in authorizedPatients"
              :key="patient.id"
              :label="patient.name"
              :value="patient.id"
          ></el-option>
        </el-select>
        <div v-if="authorizedPatients.length === 0">暂无授权患者数据</div>
      </div>
    </div>

    <div v-if="selectedPatientId" class="patient-data">
      <div class="authorization-status">
        <h3>患者授权状态: {{ getAuthorizationText() }}</h3>
        <div v-if="patientData.response">授权响应: {{ patientData.response }}</div>
        <div>申请人: {{ userStore.username }}</div>
        <button
            v-if="!patientAuthorizationStatus"
            @click="requestAuthorization"
            class="request-auth-btn"
        >
          请求授权
        </button>
      </div>
    </div>
    <div v-if="userStore?.role === '授权医护人员'" class="doctor-features">
    </div>
    <div v-else-if="userStore?.role === '健康管理师'" class="manager-features">
      <div class="data-categories">
        <el-tabs v-model="activeTab" type="border-card">

        <el-tab-pane label="医疗记录" name="records">
          <div class="records-list">
            <el-table
              :data="patientRecords"
              border
              v-loading="recordsLoading"
              element-loading-text="加载中..."
              class="records-table"
            >
              <el-table-column prop="id" label="记录ID" width="100"></el-table-column>
              <el-table-column prop="type" label="记录类型"></el-table-column>
              <el-table-column prop="createTime" label="创建时间"></el-table-column>
              <el-table-column label="操作" width="120">
                <template #default="scope">
                  <el-button

                    type="primary"
                    size="small"
                    @click="viewRecordDetails(scope.row)"
                    style="margin-right: 8px"
                  >
                    查看详情
                  </el-button>
                  <el-button
                    type="danger"
                    size="small"
                    @click="handleDelete(scope.row.id)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
              <template #empty>
                <div class="no-records">
                  <el-empty description="暂无记录数据"></el-empty>
                </div>
              </template>
            </el-table>

          <!-- 记录详情模态框 -->
          <el-dialog v-model="dialogVisible" title="记录详情" width="60%">
  <template #footer>
    <div class="dialog-footer">
      <el-button v-if="!isEditing && hasPermission(currentRecord.type, 'update')" @click="handleEdit">编辑</el-button>
      <el-button v-if="isEditing" type="primary" @click="handleSave">保存</el-button>
      <el-button v-if="isEditing" @click="handleCancel">取消</el-button>
    </div>
  </template>
            <el-descriptions :column="1" v-if="currentRecord && !isEditing">
              <el-descriptions-item label="记录ID">{{ currentRecord.id }}</el-descriptions-item>
              <el-descriptions-item label="记录类型">{{ currentRecord.type }}</el-descriptions-item>
              <el-descriptions-item label="创建时间">{{ currentRecord.createTime }}</el-descriptions-item>

              <!-- 过敏史特有字段 -->
              <template v-if="currentRecord.type === '过敏史'">
                <el-descriptions-item label="过敏原">{{ currentRecord.originalData.allergen || '无' }}</el-descriptions-item>
                <el-descriptions-item label="避免措施">{{ currentRecord.originalData.avoidanceMethod || '无' }}</el-descriptions-item>
                <el-descriptions-item label="禁用药物">{{ currentRecord.originalData.forbiddenDrugs || '无' }}</el-descriptions-item>
                <el-descriptions-item label="治疗药物">{{ currentRecord.originalData.treatmentDrugs || '无' }}</el-descriptions-item>
                <el-descriptions-item label="备注">{{ currentRecord.originalData.remarks || '无' }}</el-descriptions-item>
              </template>

              <!-- 家族病史特有字段 -->
              <template v-else-if="currentRecord.type === '家族病史'">
                <el-descriptions-item label="病人姓名">{{ currentRecord.originalData.patientName }}</el-descriptions-item>
                <el-descriptions-item label="疾病名称">{{ currentRecord.originalData.diseaseName || '无' }}</el-descriptions-item>
                <el-descriptions-item label="亲属关系">{{ currentRecord.originalData.relationship || '无' }}</el-descriptions-item>
                <el-descriptions-item label="发作频率">{{ currentRecord.originalData.onsetFrequency || '无' }}</el-descriptions-item>
                <el-descriptions-item label="备注">{{ currentRecord.originalData.remarks || '无' }}</el-descriptions-item>
              </template>

              <!-- 用药记录特有字段 -->
              <template v-else-if="currentRecord.type === '用药记录'">
                <el-descriptions-item label="药物名称">{{ currentRecord.originalData.medicationName || '无' }}</el-descriptions-item>
                <el-descriptions-item label="用法用量">{{ currentRecord.originalData.usageAndDosage || '无' }}</el-descriptions-item>
                <el-descriptions-item label="用药原因">{{ currentRecord.originalData.medicationReason || '无' }}</el-descriptions-item>
                <el-descriptions-item label="用药结果">{{ currentRecord.originalData.medicationResult || '无' }}</el-descriptions-item>
              </template>

              <!-- 健康指标特有字段 -->
              <template v-else-if="currentRecord.type === '健康指标'">
                <el-descriptions-item label="身高">{{ currentRecord.originalData.height || '无' }}</el-descriptions-item>
                <el-descriptions-item label="体重">{{ currentRecord.originalData.weight || '无' }}</el-descriptions-item>
                <el-descriptions-item label="BMI">{{ currentRecord.originalData.bmi || '无' }}</el-descriptions-item>
                <el-descriptions-item label="血糖">{{ currentRecord.originalData.bloodSugar || '无' }}</el-descriptions-item>
                <el-descriptions-item label="血压">{{ currentRecord.originalData.bloodPressure || '无' }}</el-descriptions-item>
                <el-descriptions-item label="心率">{{ currentRecord.originalData.heartRate || '无' }}</el-descriptions-item>
              </template>

              <!-- 体检报告特有字段 -->
              <template v-else-if="currentRecord.type === '体检报告'">
                <el-descriptions-item label="异常指标">{{ currentRecord.originalData.abnormalIndicators || '无' }}</el-descriptions-item>
                <el-descriptions-item label="病情分析">{{ currentRecord.originalData.condition || '无' }}</el-descriptions-item>
                <el-descriptions-item label="医嘱">{{ currentRecord.originalData.medicalAdvice || '无' }}</el-descriptions-item>
                <el-descriptions-item label="体检机构">{{ currentRecord.originalData.examinationInstitution || '无' }}</el-descriptions-item>
                <el-descriptions-item label="体检医生">{{ currentRecord.originalData.examinationDoctor || '无' }}</el-descriptions-item>
              </template>

              <!-- 既往病史特有字段 -->
              <template v-else-if="currentRecord.type === '既往病史'">
                <el-descriptions-item label="疾病名称">{{ currentRecord.originalData.diseaseName || '无' }}</el-descriptions-item>
                <el-descriptions-item label="疾病描述">{{ currentRecord.originalData.symptoms || '无' }}</el-descriptions-item>
                <el-descriptions-item label="病因">{{ currentRecord.originalData.cause || '无' }}</el-descriptions-item>
                <el-descriptions-item label="治疗过程">{{ currentRecord.originalData.treatmentProcess || '无' }}</el-descriptions-item>
                <el-descriptions-item label="后遗症">{{ currentRecord.originalData.hasSequel || '无' }}</el-descriptions-item>
              </template>


            </el-descriptions>

              <!-- 编辑表单 -->
              <el-form v-else-if="currentRecord && isEditing" :model="editedRecord" label-width="120px">
                <!-- 过敏史编辑字段 -->
                <template v-if="currentRecord.type === '过敏史'">
                  <el-form-item label="过敏原">
                    <el-input v-model="editedRecord.allergen"></el-input>
                  </el-form-item>
                  <el-form-item label="避免措施">
                    <el-input v-model="editedRecord.avoidanceMethod"></el-input>
                  </el-form-item>
                  <el-form-item label="禁用药物">
                    <el-input v-model="editedRecord.forbiddenDrugs"></el-input>
                  </el-form-item>
                  <el-form-item label="治疗药物">
                    <el-input v-model="editedRecord.treatmentDrugs"></el-input>
                  </el-form-item>
                  <el-form-item label="备注">
                    <el-input v-model="editedRecord.remarks"></el-input>
                  </el-form-item>
                </template>

                <!-- 家族病史编辑字段 -->
                <template v-else-if="currentRecord.type === '家族病史'">
                  <el-form-item label="疾病名称">
                    <el-input v-model="editedRecord.diseaseName"></el-input>
                  </el-form-item>
                  <el-form-item label="亲属关系">
                    <el-input v-model="editedRecord.relationship"></el-input>
                  </el-form-item>
                  <el-form-item label="发作频率">
                    <el-input v-model="editedRecord.onsetFrequency"></el-input>
                  </el-form-item>
                  <el-form-item label="备注">
                    <el-input v-model="editedRecord.remarks"></el-input>
                  </el-form-item>
                </template>

                <!-- 用药记录编辑字段 -->
                <template v-else-if="currentRecord.type === '用药记录'">
                  <el-form-item label="药物名称">
                    <el-input v-model="editedRecord.medicationName"></el-input>
                  </el-form-item>
                  <el-form-item label="用法用量">
                    <el-input v-model="editedRecord.usageAndDosage"></el-input>
                  </el-form-item>
                  <el-form-item label="用药原因">
                    <el-input v-model="editedRecord.medicationReason"></el-input>
                  </el-form-item>
                  <el-form-item label="用药结果">
                    <el-input v-model="editedRecord.medicationResult"></el-input>
                  </el-form-item>
                </template>

                <!-- 健康指标编辑字段 -->
                <template v-else-if="currentRecord.type === '健康指标'">
                  <el-form-item label="身高">
                    <el-input v-model="editedRecord.height"></el-input>
                  </el-form-item>
                  <el-form-item label="体重">
                    <el-input v-model="editedRecord.weight"></el-input>
                  </el-form-item>
                  <el-form-item label="BMI">
                    <el-input v-model="editedRecord.bmi"></el-input>
                  </el-form-item>
                  <el-form-item label="血糖">
                    <el-input v-model="editedRecord.bloodSugar"></el-input>
                  </el-form-item>
                  <el-form-item label="血压">
                    <el-input v-model="editedRecord.bloodPressure"></el-input>
                  </el-form-item>
                  <el-form-item label="心率">
                    <el-input v-model="editedRecord.heartRate"></el-input>
                  </el-form-item>
                </template>

                <!-- 体检报告编辑字段 -->
                <template v-else-if="currentRecord.type === '体检报告'">
                  <el-form-item label="异常指标">
                    <el-input v-model="editedRecord.abnormalIndicators"></el-input>
                  </el-form-item>
                  <el-form-item label="病情分析">
                    <el-input v-model="editedRecord.condition"></el-input>
                  </el-form-item>
                  <el-form-item label="医嘱">
                    <el-input v-model="editedRecord.medicalAdvice"></el-input>
                  </el-form-item>
                  <el-form-item label="体检机构">
                    <el-input v-model="editedRecord.examinationInstitution"></el-input>
                  </el-form-item>
                  <el-form-item label="体检医生">
                    <el-input v-model="editedRecord.examinationDoctor"></el-input>
                  </el-form-item>
                </template>

                <!-- 既往病史编辑字段 -->
                <template v-else-if="currentRecord.type === '既往病史'">
                  <el-form-item label="疾病名称">
                    <el-input v-model="editedRecord.diseaseName"></el-input>
                  </el-form-item>
                  <el-form-item label="疾病描述">
                    <el-input v-model="editedRecord.symptoms"></el-input>
                  </el-form-item>
                  <el-form-item label="病因">
                    <el-input v-model="editedRecord.cause"></el-input>
                  </el-form-item>
                  <el-form-item label="治疗过程">
                    <el-input v-model="editedRecord.treatmentProcess"></el-input>
                  </el-form-item>
                  <el-form-item label="后遗症">
                    <el-input v-model="editedRecord.hasSequel"></el-input>
                  </el-form-item>
                </template>
              </el-form>
          </el-dialog>
          </div>
        </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
</template>

<script setup>
import { useUserStore } from '@/stores/user'
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';

import { ElSelect, ElOption, ElTabs, ElTabPane, ElButton, ElMessage, ElMessageBox, ElTable, ElTableColumn, ElEmpty, ElDialog, ElDescriptions, ElDescriptionsItem } from 'element-plus';
import axios from 'axios';

// 初始化路由和状态管理
const router = useRouter();
const userStore = useUserStore();
// 调试开关
const showDebugInfo = ref(true);

// 确保store和userInfo已初始化
const hasValidUser = computed(() => {
  const value = userStore?.role;
  console.log('computed hasValidUser:', value);
  return value;
});

// 调试日志 - 检查用户状态
console.log('DoctorView用户状态:', { isLoggedIn: userStore.isLoggedIn, role: userStore.role, id: userStore.id });

// 状态变量
const selectedPatientId = ref('');
const activeTab = ref('records');
const patientData = ref({});
const authorizedPatients = ref([]);
const patientAuthorizationStatus = ref('unauthorized'); // unauthorized, applied, authorized
const patientRecords = ref([]); // 患者记录数据
const recordsLoading = ref(false); // 记录加载状态
const dialogVisible = ref(false); // 详情对话框显示状态
const currentRecord = ref(null); // 当前查看的记录
const isEditing = ref(false); // 是否编辑模式
const editedRecord = ref(null); // 编辑的数据副本
const userPermissions = ref({}); // 用户权限数据

// 计算属性
const hasAccessPermission = computed(() => {
  const result = ['授权医护人员', '健康管理师'].includes(userStore.role);
  console.log('computed hasAccessPermission:', result, '当前角色:', userStore.role);
  return result;
});

const canEditData = computed(() => {
  const result = userStore.userInfo?.role === '医护人员';
  console.log('computed canEditData:', result);
  return result;
});

// 权限检查方法
const hasPermission = (recordType, action) => {
    if (!userPermissions.value || !userPermissions.value[recordType]) {
      console.warn(`No permissions defined for record type: ${recordType}`);
      return false;
    }
    
    const permissionValue = userPermissions.value[recordType][action];
    // 支持多种权限值类型: boolean, string '1'/'0', number 1/0
    return permissionValue === true || permissionValue === '1' || permissionValue === 1;
  }

// 加载用户权限
// 获取用户授权列表
const loadAuthorizations = async (patientId) => {
  try {
    const token = localStorage.getItem('token');
    const response = await axios.get(`http://localhost:8080/api/patients/${patientId}/authorizations`, {
      headers: { 'Authorization': `Bearer ${token}` }
    });
    console.log("用户授权表原始数据：", response.data.data);
      console.log("完整API响应：", response);
      console.log("包含的记录类型：", Object.keys(response.data.data || {}));
    return response.data.data || [];

  } catch (error) {
    console.error('加载授权列表失败:', error);
    return [];
  }
};

// 加载用户权限
const loadUserPermissions = async (patientId) => {
  try {
    // 获取当前患者的授权记录
    const authorizations = await loadAuthorizations(patientId);
    console.log('Backend authorization raw data:', authorizations);
    console.log('Authorizations完整数据:', authorizations);
      console.log('Authorizations数据类型:', typeof authorizations);
      console.log('Authorizations是否为数组:', Array.isArray(authorizations));
      console.log('Authorizations内容:', JSON.stringify(authorizations, null, 2));
      console.log('Searching for patientId:', patientId);
    // 从授权数组中获取第一个授权记录
      const authRecord = authorizations[0] || {};
      console.log('当前授权记录:', authRecord);

      // 提取权限字段和记录类型
      const { update = '', look = '', delete: del = '' } = authRecord;
      console.log('权限字段 - update:', update, 'look:', look, 'delete:', del);

      // 解析权限的辅助函数
      const parsePermission = (permissionStr, type) => {
        return permissionStr && permissionStr.split(',').map(t => t.trim()).includes(type);
      };

      // 提取所有唯一的记录类型
      const extractRecordTypes = () => {
        const types = new Set();
        [update, look, del].forEach(permissionStr => {
          if (permissionStr) {
            permissionStr.split(',').forEach(type => {
              if (type.trim()) types.add(type.trim());
            });
          }
        });
        return Array.from(types);
      };

      const allRecordTypes = extractRecordTypes();
      console.log('提取到的所有记录类型:', allRecordTypes);

      // 初始化权限
      const formattedPermissions = {};
      allRecordTypes.forEach(recordType => {
        formattedPermissions[recordType] = {
          look: parsePermission(look, recordType),
          update: parsePermission(update, recordType),
          delete: parsePermission(del, recordType)
        };
        console.log(`已设置权限: ${recordType} =`, formattedPermissions[recordType]);
      });
    
    userPermissions.value = formattedPermissions;
    console.log('Formatted user permissions:', userPermissions.value);
  } catch (error) {
    console.error('加载用户权限失败:', error);
    userPermissions.value = {};
  }
};

// 方法
const viewRecordDetails = (record) => {
  if (!hasPermission(record.type, 'look')) {
    ElMessage.error('你无权限');
    return;
  }
  currentRecord.value = record;
  editedRecord.value = JSON.parse(JSON.stringify(record.originalData)); // 深拷贝原始数据
  dialogVisible.value = true;
};

const handleEdit = () => {
  isEditing.value = true;
};

const handleCancel = () => {
  isEditing.value = false;
  editedRecord.value = JSON.parse(JSON.stringify(currentRecord.value.originalData)); // 恢复原始数据
};

const handleDelete = async (recordId) => {
  const record = patientRecords.value.find(r => r.id === recordId);
  if (!record || !hasPermission(record.type, 'delete')) {
    ElMessage.error('你无权限');
    return;
  }
  try {
    const confirmResult = await ElMessageBox.confirm(
      '确定要删除这条记录吗？此操作不可撤销。',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    if (confirmResult === 'confirm') {
      const token = localStorage.getItem('token');
      const response = await axios.delete(`http://localhost:8080/api/patients/records/${recordId}`, {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });

      if (response.data.success) {
        ElMessage.success('记录删除成功');
        // 从列表中移除删除的记录
        patientRecords.value = patientRecords.value.filter(record => record.id !== recordId);
        // 如果删除的是当前正在查看的记录，关闭对话框
        if (currentRecord.value && currentRecord.value.id === recordId) {
          dialogVisible.value = false;
          currentRecord.value = null;
        }
      } else {
        ElMessage.error(`删除失败: ${response.data.message}`);
      }
    }
  } catch (error) {
    if (error.name !== 'Error') {
      console.error('删除记录失败:', error);
      ElMessage.error('删除操作失败，请重试');
    }
  }
};

const handleSave = async () => {
      // 根据记录类型组合detail字段
      const recordType = currentRecord.value.type;
      console.log('当前记录类型:', recordType);
      let fields = [];

      // 添加调试日志诊断fields为空问题
      console.log('当前记录类型:', recordType);
      console.log('editedRecord.value数据:', editedRecord.value);
      console.log('是否进入默认分支:', !['过敏史', '家族病史', '用药记录', '健康指标', '体检报告', '既往病史'].includes(recordType));

      switch(recordType) {
        case '过敏史':
          fields = [
            editedRecord.value.allergen || '无',
            editedRecord.value.forbiddenDrugs || '无',
            editedRecord.value.treatmentDrugs || '无',
            editedRecord.value.avoidanceMethod || '无',
            editedRecord.value.remarks || '无'
          ];
          break;
        case '家族病史':
          fields = [
            editedRecord.value.diseaseName || '无',
            editedRecord.value.relationship || '无',
            editedRecord.value.onsetFrequency || '无',
            editedRecord.value.remarks || '无'
          ];
          break;
        case '用药记录':
          fields = [
            editedRecord.value.medicationName || '无',
            editedRecord.value.usageAndDosage || '无',
            editedRecord.value.medicationReason || '无',
            editedRecord.value.medicationResult || '无'
          ];
          break;
        case '健康指标':
          fields = [
            editedRecord.value.height || '无',
            editedRecord.value.weight || '无',
            editedRecord.value.bmi || '无',
            editedRecord.value.bloodSugar || '无',
            editedRecord.value.bloodPressure || '无',
            editedRecord.value.heartRate || '无'
          ];
          break;
        case '体检报告':
          fields = [
            editedRecord.value.abnormalIndicators || '无',
            editedRecord.value.condition || '无',
            editedRecord.value.medicalAdvice || '无',
            editedRecord.value.examinationInstitution || '无',
            editedRecord.value.examinationDoctor || '无'
          ];
          break;
        case '既往病史':
          fields = [
            editedRecord.value.diseaseName || '无',
            editedRecord.value.symptoms || '无',
            editedRecord.value.cause || '无',
            editedRecord.value.treatmentProcess || '无',
            editedRecord.value.hasSequel || '无'
          ];
          break;
        default:
          fields = [];
      }

      // 直接赋值detail字段并添加调试日志
        editedRecord.value.detail = fields.join('|');
        console.log('生成的detail字段:', fields.join('|'));
  try {
    const token = localStorage.getItem('token');
    const response = await axios.put(`http://localhost:8080/api/patients/records/${currentRecord.value.id}`, editedRecord.value, {
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    });

    if (response.data.success) {
      ElMessage.success('记录更新成功');
      currentRecord.value.originalData = {...editedRecord.value};
      isEditing.value = false;
      // 更新列表中的记录
      const index = patientRecords.value.findIndex(r => r.id === currentRecord.value.id);
      if (index !== -1) {
        patientRecords.value[index].originalData = {...editedRecord.value};
      }
    } else {
      ElMessage.error(`更新失败: ${response.data.message}`);
    }
  } catch (error) {
    console.error('保存记录失败:', error);
    ElMessage.error(`保存失败: ${error.response?.data?.message || error.message}`);
  }
};


const goToLogin = () => {
  console.log('执行goToLogin');
  router.push('/login');
};


const loadAuthorizedPatients = async () => {
  const token = localStorage.getItem('token');
  console.log('加载授权患者列表，token:', token ? '存在' : '不存在');
  try {
    console.log('发起请求: GET /api/doctors/patients');
    const response = await fetch('http://localhost:8080/api/doctors/patients', {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    console.log('响应状态:', response.status, response.statusText);
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      console.error('请求失败响应数据:', errorData);
      throw new Error(`HTTP错误: ${response.status} - ${errorData.message || '未知错误'}`);
    }
    const result = await response.json();
    console.log('授权患者列表响应数据:', result);
    console.log('授权患者列表响应数据类型:', typeof result.data, '是否为数组:', Array.isArray(result.data));
    if (result.success) {
      authorizedPatients.value = result.data.patients;
      console.log('赋值后 authorizedPatients 的值:', authorizedPatients.value);
      console.log('赋值后 authorizedPatients 的类型:', typeof authorizedPatients.value, '是否为数组:', Array.isArray(authorizedPatients.value));
      console.log('授权患者数量:', authorizedPatients.value.length);
      if (authorizedPatients.value.length === 0) {
        console.log('获取到的授权患者列表为空');
      }
    } else {
      ElMessage.error('获取患者列表失败: ' + result.message);
    }
  } catch (error) {
    console.error('加载授权患者失败:', error);
    ElMessage.error('加载患者列表失败，请重试');
    console.error('错误详情:', {
      message: error.message,
      stack: error.stack,
      tokenAvailable: token ? true : false
    });
  }
};

const loadPatientData = async () => {
  await loadUserPermissions(selectedPatientId.value);
  const applicant = userStore.id; // applicant: 申请授权的医生ID
  console.log('加载患者数据，医生ID(applicant):', applicant, '患者ID:', selectedPatientId.value);
  if (!applicant || !selectedPatientId.value) {
    ElMessage.error('医生ID和患者ID不能为空');
    return;
  }
  try {
    // 修正API路径以匹配后端DoctorController的@RequestMapping
    const response = await axios.get(`http://localhost:8080/api/doctors/patients/${selectedPatientId.value}/data/${applicant}`);
    const data = response.data;
    console.log(data.code)
    // 检查后端返回的状态码
    if (data.code === 200) {
      patientData.value = data.data;
      patientAuthorizationStatus.value = 'authorized';
      console.log('患者数据加载成功:', data.data);
      // 加载患者记录
      loadPatientRecords();
    } else {
      ElMessage.error(`获取患者数据失败:该用户未授权`);
      patientAuthorizationStatus.value = false;
    }
  } catch (error) {
    console.error('加载患者数据失败:', error);
    ElMessage.error(`加载患者数据失败: ${error.response?.data?.msg || error.message}`);
  }
};

const loadPatientRecords = async () => {
  if (!selectedPatientId.value) return;
  
  recordsLoading.value = true;
  try {
    const token = localStorage.getItem('token');
    const response = await axios.get(`http://localhost:8080/api/patients/${selectedPatientId.value}/records`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    
    // 解析后端Result格式
    if (response.data.success) {
      const rawRecords = response.data.data; // 获取嵌套的data对象
      console.log('原始记录数据:', rawRecords);

      // 展平分类记录为表格所需格式
      const flattenedRecords = [];
      Object.keys(rawRecords).forEach(category => {
        const records = rawRecords[category];
        
        if (Array.isArray(records)) {
          records.forEach(record => {
            flattenedRecords.push({
              id: record.recordId,
              type: record.recordType,
              createTime: record.recordDate,
              content: record.detail || record.diseaseName || JSON.stringify(record),
              originalData: record
            });
          });
        }
      });
      
      patientRecords.value = flattenedRecords;
      console.log('转换后记录数据:', flattenedRecords);
    } else {
      ElMessage.error(`获取患者记录失败: ${response.data.message || '未知错误'}`);
      patientRecords.value = [];
    }
  } catch (error) {
    console.error('加载患者记录失败:', error);
    ElMessage.error(`加载患者记录失败: ${error.response?.data?.message || error.message}`);
    patientRecords.value = [];
  } finally {
    recordsLoading.value = false;
  }
};

const getAuthorizationText = () => {
  if (patientAuthorizationStatus.value === 'authorized') {
    return '已授权';
  } else if (patientAuthorizationStatus.value === 'applied') {
    return '已申请';
  }
  return '未授权';
};

const requestAuthorization = async () => {
  // applicant: 医生ID, response: 被申请的患者ID
  if (!selectedPatientId.value || !userStore.id) {
    ElMessage.error('请选择患者并确保用户已登录');
    return;
  }
  try {
    const token = localStorage.getItem('token');
    console.log("applicant:"+userStore.id);
    console.log("response:"+selectedPatientId.value);
    const requestData = {
      applicant: userStore.id,
      response: selectedPatientId.value
    };
    console.log('请求授权参数:', requestData);
    const response = await axios.post(`http://localhost:8080/api/authorize/request`, requestData, {
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    });
    console.log('授权请求响应:', response.data);
    if (response.data.code === 200) {
      if (response.data.message && response.data.message.includes('已存在申请')) {
        patientAuthorizationStatus.value = 'applied';
        ElMessage.info('已存在申请');
      } else {
        patientAuthorizationStatus.value = 'applied';
        ElMessage.success('授权请求已发送成功');
      }
      getAuthorizationStatus();
    } else {
      ElMessage.error(`授权请求失败: ${response.data.message || '未知错误'}`);
    }
  } catch (error) {
    console.error('授权请求失败详情:', {
      status: error.response?.status,
      statusText: error.response?.statusText,
      data: error.response?.data,
      requestData: { applicant: userStore.id.toString(), response: selectedPatientId.value.toString() },
      headers: error.config?.headers,
      url: error.config?.url,
      message: error.message
    });
    ElMessage.error(`授权请求失败: ${error.response?.data?.msg || error.message || '服务器内部错误'}`);
  }
}

const getAuthorizationStatus = async () => {
  if (!selectedPatientId.value || !userStore.id) return;
  try {
    const token = localStorage.getItem('token');
    console.log('查询授权状态请求参数:', { applicant: userStore.id, patientId: selectedPatientId.value, token: token ? '存在' : '缺失' });
    // 恢复原始API路径结构，添加认证头和查询参数
    const response = await axios.get(`http://localhost:8080/api/patients/${selectedPatientId.value}/authorization-status`, {
      params: {
        applicant: userStore.id
      },
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    console.log('授权状态响应:', response.data);
    if (response.data.data === true) {
      patientAuthorizationStatus.value = 'authorized';
    } else if (response.data.data === 'applied') {
      patientAuthorizationStatus.value = 'applied';
    } else {
      patientAuthorizationStatus.value = 'unauthorized';
    }
  } catch (error) {
    console.error('查询授权状态失败详情:', {
      status: error.response?.status,
      data: error.response?.data,
      message: error.message,
      url: error.config?.url
    });
    ElMessage.error(`查询授权状态失败: ${error.response?.data?.message || error.message}`);
  }
};

// 页面加载时执行
onMounted(() => {
  console.log('DoctorView mounted - 开始执行');
  console.log('用户角色:', userStore.role, '是否登录:', userStore.isLoggedIn);
  if (!userStore?.role || !['授权医护人员', '健康管理师'].includes(userStore.role)) {
    console.log('用户角色不符合要求，重定向到登录页');
    goToLogin();
    return;
  }

  // 检查权限
  if (!hasAccessPermission.value) {
    console.log('用户没有访问权限');
    return;
  }

  // 加载授权患者列表
  loadAuthorizedPatients();
});
</script>
<style scoped>
/* 原有样式保持不变 */
.debug-info {
  background-color: #fff3cd;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 20px;
  font-family: monospace;
  font-size: 14px;
}
</style>

<style scoped>
.doctor-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e5e7eb;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.role-tag {
  padding: 4px 8px;
  border-radius: 4px;
  background-color: #e0f2fe;
  color: #0369a1;
  font-size: 14px;
}

.logout-btn {
  padding: 6px 12px;
  background-color: #ef4444;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.auth-required,
.no-permission {
  text-align: center;
  padding: 50px 0;
}

.login-btn {
  padding: 8px 16px;
  background-color: #3b82f6;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
}

.main-content {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  padding: 20px;
}

.patient-selection {
  margin-bottom: 20px;
}

.authorization-status {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f0f9ff;
  border-radius: 8px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.request-auth-btn {
  padding: 8px 16px;
  background-color: #3b82f6;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.data-categories {
  margin-top: 20px;
}

.records-list {
  padding: 10px;
}

.records-table {
  width: 100%;
  margin-top: 10px;
}

.no-records {
  text-align: center;
  padding: 40px 0;
}
</style>